#include "serialporthelper.h"

SerialPortHelper::SerialPortHelper(QObject *parent) : QObject(parent)
{
    serialPort = new QSerialPort(this);
    connect(serialPort, &QSerialPort::readyRead, this, &SerialPortHelper::handleReadyRead);

    // 定时器用于检查串口状态变化
    QTimer *portStateTimer = new QTimer(this);
    connect(portStateTimer, &QTimer::timeout, this, [this]() {
        bool isOpen = serialPort->isOpen();
        if (isOpen!= m_lastPortState) {
            m_lastPortState = isOpen;
            emit portStateChanged(isOpen);
        }
    });
    portStateTimer->start(500);
}

QStringList SerialPortHelper::getAvailablePorts()
{
    QStringList portNames;
    const auto availablePorts = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &portInfo : availablePorts) {
        portNames.append(portInfo.portName());
    }
    return portNames;
}

bool SerialPortHelper::openSerialPort(const QString &portName, int baudRate, int dataBits, int parity, int stopBits)
{
    serialPort->setPortName(portName);
    serialPort->setBaudRate(static_cast<QSerialPort::BaudRate>(baudRate));
    serialPort->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
    serialPort->setParity(static_cast<QSerialPort::Parity>(parity));
    serialPort->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
    return serialPort->open(QIODevice::ReadWrite);
}

void SerialPortHelper::closeSerialPort()
{
    if (serialPort->isOpen()) {
        serialPort->close();
    }
}

void SerialPortHelper::writeData(const QByteArray &data)
{
    if (serialPort->isOpen()) {
        serialPort->write(data);
    }
}

bool SerialPortHelper::isPortOpen()
{
    return serialPort->isOpen();
}

int SerialPortHelper::getBaudRate()
{
    if (serialPort->isOpen()) {
        return serialPort->baudRate();
    }
    return -1;
}

int SerialPortHelper::getDataBits()
{
    if (serialPort->isOpen()) {
        return serialPort->dataBits();
    }
    return -1;
}

int SerialPortHelper::getParity()
{
    if (serialPort->isOpen()) {
        return serialPort->parity();
    }
    return -1;
}

int SerialPortHelper::getStopBits()
{
    if (serialPort->isOpen()) {
        return serialPort->stopBits();
    }
    return -1;
}

void SerialPortHelper::handleReadyRead()
{
    QByteArray data = serialPort->readAll();
    emit dataReceived(data);
}
